<!--  -->
<template>
  <div class="flex column" style="width: 100%; height: 100%">
    <slot name="title"></slot>
    <div class="chatBox flex column grow" ref="chatBox" @scroll="tumble">
      <div class="chat-items-wrap flex column grow" ref="chatWrap">
        <div
          class="noMore flex column grow"
          v-if="messageList.length < 1"
        ></div>
        <div
          class="chat-item clear"
          v-for="item in messageList"
          :key="item.id"
          :class="['user', 'teacher'][item.userType]"
        >
          <div class="time">{{ item._publishTime }}</div>
          <div class="line1 clear">
            <span class="photo">
              <img :src="item.teacherPhoto || item.userPhoto" alt />
            </span>
            <span class="name">{{ item.teacherName || item.nickName }}</span>
            <span class="cerName hide"> 证书编号{{ item.cerName }} </span>
          </div>
          <div class="line2 clear">
            <div class="content" v-html="item.content"></div>
            <template v-if="item.replyList.length > 0">
              <span class="reply" v-for="i in item.replyList" :key="i.id">
                <span class="replyName"
                  >@{{ i.teacherName || i.nickName }}</span
                >
                <span v-html="i.content"></span>
                <div class="replytime">{{ i._publishTime }}</div>
              </span>
            </template>
          </div>
        </div>
      </div>
    </div>
    <div class="replyBox flex column grow shrink">
      <span class="toDown" @click="putDown" v-show="shrink.switch">
        {{ shrink.text }}
      </span>
      <textarea
        @keyup.enter="submit"
        :placeholder="howdy"
        class="flex column grow"
        v-model="content"
      ></textarea>
      <div class="toolBox flex column grow shrink clear">
        <div
          class="stockList-items top"
          v-show="listShow"
          @mouseleave="listShow = false"
        >
          <div
            class="stockList-item clear"
            v-for="item in stockList"
            :key="item.stockName"
            @click="
              choose(item.exchangeSymbols, item.stockCode, item.stockName)
            "
          >
            <span class="cell cell1" v-text="item.hqTypeLabel"></span>
            <span class="cell" v-text="item.stockCode"></span>
            <span class="cell" v-text="item.stockName"></span>
            <span class="cell cell4" v-text="item.chiSpelling"></span>
          </div>
        </div>
        <input type="text" v-model="stock" placeholder="股票代码/名称/首字母" />
        <div class="submit tr">
          {{ count }}/150
          <span @click="submit">提交</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  zstgList,
  todayZsInteractionCount,
  getStockList,
  userClickUpdate,
  addZstg,
} from "../api/api";

import * as fn from "../script/utils";
import debounce from "lodash/debounce";
import { Toast } from "vant";
import format from "date-fns/format";
const { token, version, productId, userId } = fn.getUrlParams();
console.log(token, "===token==");
import behavior from "../script/behavior";
const userData = { ...behavior };

export default {
  data() {
    return {
      stockList: [],
      messageList: [],
      sinceId: "",
      content: "",
      count: 150,
      listShow: false,
      version: version,
      stock: "",
      shrink: {
        switch: false,
        aggregate: 0,
        text: "回到底部",
      },
      numQuestions: "", //已提问次数
      howdy: "", //剩余次数提示语
    };
  },

  components: {},
  computed: {},
  watch: {
    numQuestions(num) {
      this.howdy =
        num >= 3 ? "今日提问次数已上限" : `您还有${3 - num}次提问机会`;
    },
    stock: debounce(async function () {
      if (this.stock.length >= 1) {
        await getStockList({ content: this.stock }).then((back) => {
          let stocks = back.stocks;
          if (stocks.length > 0) {
            this.stockList = stocks;
            this.listShow = true;
          }
        });
      } else {
        this.listShow = false;
      }
    }, 500),
    content: debounce(function () {
      if (this.content.length > 150) {
        this.content = this.content.substr(0, 150);
        return;
      }
      this.count = 150 - this.content.length;
      let day = localStorage.getItem("day");
      if (
        (version != 5 && this.numQuestions >= 3 && this.content.trim(),
        day != new Date().getDate())
      ) {
        this.todayZsInteractionCount();
      }
    }, 500),
  },
  mounted() {
    this.todayZsInteractionCount();
    this.zstgList();
    this.$nextTick(() => {
      this.putDown();
      this.pushMessage();
      document.body.addEventListener("click", (e) => {
        if (e.target.className === "_stockCode") {
          var type = e.target.getAttribute("data-market");
          var code = e.target.getAttribute("data-code");  
          this.link(type, code);
        }
      });
    });
  },

  methods: {
    async userClick() {
      userData.event[0].eventSubject.extend.questionStr = fn.utf16toEntities(
        this.content
      );
      if (!fn.isOneMinu()) return;
      await userClickUpdate(userData).then((back) => {
        if (back.status == 1) {
          let data = back.data;
        }
      });
    },
    tumble: debounce(function (e) {
      const { path } = e;
      if (
        path[0].scrollTop + path[0].clientHeight <
        path[0].scrollHeight - 10
      ) {
        this.shrink.switch = true;
      } else {
        this.shrink.switch = false;
        this.shrink.aggregate = 0;
        this.shrink.text = "回到底部";
      }
      if (path[0].scrollTop < 20) {
        this.zstgList();
      }
    }, 300),
    //跳转个股详情
    link(type, code) {
      type = type == "SS" ? "1" : "0";
      window.prompt(
        "",
        `up://["open.stock",${Date.now()},{"setcode":"${type}","code":"${code}","type":"首页"}]`
      );
    },
    choose(exchangeSymbols, stockCode, stockName) {
      this.content = `${this.content}$${exchangeSymbols}-${
        stockCode + stockName
      }$`;
      behavior.event[0].eventSubject.stockCode =
        behavior.event[0].eventSubject.stockCode + "," + stockCode;
      behavior.event[0].eventSubject.stockName =
        behavior.event[0].eventSubject.stockName + "," + stockName;
      this.reset();
    },
    reset() {
      this.listShow = false;
      this.stock = "";
      this.stockList = [];
    },
    //聊天列表
    async zstgList() {
      const box = this.$refs.chatBox;
      const boxed = box.scrollHeight; //记住上一次的滚动位置
      await zstgList({
        productId: productId || window.localStorage.getItem("productId"),
        limit: 20,
        clientCentralToken: token,
        sinceId: this.sinceId,
      }).then((back) => {
        if (back.status == 1) {
          let data = back.data;
          if (data.length < 1) return;
          this.messageList = data
            .map((item) => {
              item.content = fn.higihLighttStock(
                fn.entitiestoUtf16(item.content)
              );
              item._publishTime = fn.timeFormat(item.ctime, "yyyy-MM-dd HH:mm");
              if (item.replyList.length > 0) {
                item.replyList[0]._publishTime = fn.timeFormat(
                  item.replyList[0].ctime,
                  "yyyy-MM-dd HH:mm"
                );
                item.replyList[0].content = fn.higihLighttStock(
                  fn.entitiestoUtf16(item.replyList[0].content)
                );
              }
              return item;
            })
            .concat(this.messageList);

          //数据加载更多后定位滚动位置
          this.$nextTick(() => {
            box.scrollTop = box.scrollHeight - boxed;
          });
          this.sinceId = this.messageList[0].id;
        }
      });
    },
    //已提问次数
    async todayZsInteractionCount() {
      await todayZsInteractionCount({
        productId: productId || window.localStorage.getItem("productId"),
        clientCentralToken: token,
      }).then((back) => {
        if (back.status == 1) {
          let data = back.data;
          if (version == 4) {
            this.numQuestions = data;
            if (data >= 3) {
              window.localStorage.setItem("day", new Date().getDate());
            }
          } else {
            this.howdy = "请输入提问内容";
          }
        }
      });
    },
    //发送信息
    submit: debounce(async function () {
      if (version != 5 && this.numQuestions >= 3) {
        return Toast("今日提问次数已上限");
      }
      if (!this.content.trim()) {
        this.content = "";
        return Toast("输入不能为空");
      }
      await addZstg({
        productId: productId || window.localStorage.getItem("productId"),
        clientCentralToken: token,
        content: fn.utf16toEntities(this.content),
      }).then((back) => {
        //用户行为统计用户提问内容
        this.userClick();
        userData.event[0].eventSubject.stockCode = "";
        userData.event[0].eventSubject.stockName = "";
        this.content = "";
        this.todayZsInteractionCount();
      });
    }, 300),
    //置底
    putDown() {
      const box = this.$refs.chatBox;
      this.shrink.aggregate = 0;
      this.shrink.text = "回到底部";
      this.$nextTick(() => {
        box.scrollTop = box.scrollHeight;
      });
    },
    //推送
    pushMessage() {
      const uId = userId || window.localStorage.getItem("userId");
      const pId = productId || window.localStorage.getItem("productId");
      const key1 = `0_8_${uId}_${pId}`;
      const key2 = `0_8_0_${pId}`;
      const self = this;
      fn.creatSocket(key1, function (data) {
        self.messageList = self.messageList.concat(
          [data.zstgInteraction].map((item) => {
            item.content = fn.higihLighttStock(
              fn.entitiestoUtf16(item.content)
            );
            item._publishTime = fn.timeFormat(item.ctime, "yyyy-MM-dd HH:mm");
            if (item.replyList) {
              item.replyList[0]._publishTime = fn.timeFormat(
                item.replyList[0].ctime,
                "yyyy-MM-dd HH:mm"
              );
              item.replyList[0].content = fn.higihLighttStock(
                fn.entitiestoUtf16(item.replyList[0].content)
              );
            } else {
              item.replyList = [];
            }
            //用户行为统计
            if (item.userType) {
              //用户行为统计老师回答内容
              userData.event[0].eventSubject.extend.answerStr = item.content;
              self.userClick();
              userData.event[0].eventSubject.extend.answerStr = "";
            }
            return item;
          })
        );
        self.shrink.aggregate++;
        if (self.shrink.aggregate <= 99) {
          self.shrink.text = `有${self.shrink.aggregate}条新消息`;
        } else {
          self.shrink.text = `有99+条新消息`;
        }
        if (!self.shrink.switch) {
          self.putDown();
        }
      });
      fn.creatSocket(key2, function (data) {
        self.messageList = self.messageList.concat(
          [data.zstgInteraction].map((item) => {
            item.content = fn.higihLighttStock(
              fn.entitiestoUtf16(item.content)
            );
            item._publishTime = fn.timeFormat(item.ctime, "yyyy-MM-dd HH:mm");
            if (item.replyList) {
              item.replyList[0]._publishTime = fn.timeFormat(
                item.replyList[0].ctime,
                "yyyy-MM-dd HH:mm"
              );
              item.replyList[0].content = fn.higihLighttStock(
                fn.entitiestoUtf16(item.replyList[0].content)
              );
            } else {
              item.replyList = [];
            }
            if (item.userType) {
              //用户行为统计老师回答内容
              userData.event[0].eventSubject.extend.answerStr = item.content;
              self.userClick();
              userData.event[0].eventSubject.extend.answerStr = "";
            }

            return item;
          })
        );
        self.shrink.aggregate++;
        if (self.shrink.aggregate <= 99) {
          self.shrink.text = `有${self.shrink.aggregate}条新消息`;
        } else {
          self.shrink.text = `有99+条新消息`;
        }
        if (!self.shrink.switch) {
          self.putDown();
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.noMore {
  background: url($PIC_URL + "/tlbypcWeb/advisor/zxtg_pic.png") no-repeat center
    center;
}
.toDown {
  background-image: url($PIC_URL + "/tlbypcWeb/advisor/db_icon.png");
  background-repeat: no-repeat;
  background-position: right 10px center;
}
</style>
